﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Activation;
using DbContext;
using DbDapper;
using Utility;
using BaseCommon;
using System.Xml;
using System.Net;
using System.IO;
using System.Xml.Serialization;
using AIEventControlLibrary;
using AIEventControlLibrary.Data;

namespace AISmartEventServer
{

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Single, IncludeExceptionDetailInFaults = true)]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class AIEventManagerServer : AIEventManagerServerI
    {

        #region 人员管理
        #region 添加人员
        /// <summary>
        /// 添加人员
        /// </summary>
        /// <param name="ip">ip地址</param>
        /// <param name="port">端口</param>
        /// <param name="person">人员信息实体</param>
        /// <param name="B64FacePics">多张人脸图像</param>
        /// <returns></returns>
        public string AddPerson(string ip, int port, string Person)
        {
            if (string.IsNullOrEmpty(Person)) return "";

            string url = "http://" + ip + ":" + port + "/AddPerson";
            //PersonInfo personInfoAndB64 = new PersonInfo();
            //personInfoAndB64.Person = person;
            //personInfoAndB64.FacePics_B64 = B64FacePics;
            //string jsonpic = Newtonsoft.Json.JsonConvert.SerializeObject(personInfoAndB64);

            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(Person);
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);

            //Uid=admin&Pwd=admin&Ip=192.168.186.1&HttpPort=8091

            httpReq.Method = "POST";     //对发送的数据不使用缓存 
            using (Stream postStream = httpReq.GetRequestStream())
            {
                postStream.Write(bytes, 0, bytes.Length);
                using (WebResponse webRespon = httpReq.GetResponse())
                {
                    using (Stream s = webRespon.GetResponseStream())
                    {
                        //读取服务器端返回的消息
                        using (StreamReader sr = new StreamReader(s))
                        {
                            string sReturnString = sr.ReadToEnd();
                            if (sReturnString == "0")
                            {
                                return "ok";
                            }
                            else
                            {
                                return "No";
                            }
                        }
                    }
                }
            }
        }
        #endregion

        #region 删除人员
        /// <summary>
        /// 删除人员
        /// </summary>
        /// <param name="personID"></param>
        /// <returns></returns>
        public string DeletePersonByID(string ip, int port, long personID)
        {
            string url = "http://" + ip + ":" + port + "/DeletePersonByID?ID=" + personID + "";
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
            httpReq.Method = "POST";     //对发送的数据不使用缓存 
            using (Stream postStream = httpReq.GetRequestStream())
            {
                using (WebResponse webRespon = httpReq.GetResponse())
                {
                    using (Stream s = webRespon.GetResponseStream())
                    {
                        //读取服务器端返回的消息
                        using (StreamReader sr = new StreamReader(s))
                        {
                            string sReturnString = sr.ReadToEnd();

                            if (sReturnString == "0")
                            {
                                return "OK";
                            }
                        }
                    }
                }
            }
            return "NO";
        }
        #endregion

        #endregion

        #region  规则信息获取
        /// <summary>
        ///  规则获取
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        public  List<AiBoxSimpleChannelInfo> GetAiBoxSimpleChannels(string ip,int port)
        {
            string url = "http://" + ip + ":" + port + "/GetAiSimpleChannels";
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
            //Uid=admin&Pwd=admin&Ip=192.168.186.1&HttpPort=8091
            httpReq.Method = "POST";     //对发送的数据不使用缓存 
            using (Stream postStream = httpReq.GetRequestStream())        //发送请求头部消息
            {
                using (WebResponse webRespon = httpReq.GetResponse())
                {
                    using (Stream s = webRespon.GetResponseStream())
                    {
                        //读取服务器端返回的消息
                        using (StreamReader sr = new StreamReader(s))
                        {
                            string sReturnString = sr.ReadToEnd();
                            if (sReturnString != "")
                            {
                                var list = XmlConverter.Deserialize<List<AiBoxSimpleChannelInfo>>(sReturnString);
                                if (list != null && list.Count > 0)
                                {
                                    return list;
                                }
                            }
                        }
                    }
                }
            }
            return new List<AiBoxSimpleChannelInfo>();
        }

        #region 规则获取
        /// <summary>
        /// 获取某个通道下的规则列表
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        /// <param name="AiChannelID"></param>
        /// <returns></returns>
        public  List<SimpleRuleInfo> GetAiChannelRuleList(string ip,int port,int AiChannelID)
        {
            List<SimpleRuleInfo> ruleList = new List<SimpleRuleInfo>();
            string url = "http://" + ip + ":" + port + "/GetAiChannelRuleList?AiChannelID="+ AiChannelID;
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
            //Uid=admin&Pwd=admin&Ip=192.168.186.1&HttpPort=8091
            httpReq.Method = "POST";     //对发送的数据不使用缓存 
            using (Stream postStream = httpReq.GetRequestStream())        //发送请求头部消息
            {
                using (WebResponse webRespon = httpReq.GetResponse())
                {
                    using (Stream s = webRespon.GetResponseStream())
                    {
                        //读取服务器端返回的消息
                        using (StreamReader sr = new StreamReader(s))
                        {
                            string sReturnString = sr.ReadToEnd();
                            if (sReturnString != "")
                            {
                                var  list = XmlConverter.Deserialize<List<SimpleRuleInfo>> (sReturnString);
                                if (list != null && list.Count > 0)
                                {
                                    ruleList.AddRange(list);
                                }
                            }
                        }
                    }
                }
            }
            return ruleList;
        }
        #endregion 

        #endregion

        #region 事件查询
        /// <summary>
        /// 数据查询
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public  List<EventRecord> RecordQuery(string ip,int port,int channelId, string appRuleType, DateTime date, DateTime startTime, DateTime endTime)
        {
            string url = "http://" + ip + ":" + port + "/RecordQuery" + string.Format("?channelId={0}&appRuleType={1}&date={2}&startTime={3}&endTime={4}",
                channelId,appRuleType,date,startTime,endTime);
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
            httpReq.Method = "POST";     //对发送的数据不使用缓存 
            using (Stream postStream = httpReq.GetRequestStream())
            {
                //postStream.Write(bytes, 0, bytes.Length);
                using (WebResponse webRespon = httpReq.GetResponse())
                {
                    using (Stream s = webRespon.GetResponseStream())
                    {
                        //读取服务器端返回的消息
                        using (StreamReader sr = new StreamReader(s))
                        {
                            string sReturnString = sr.ReadToEnd();
                            if (sReturnString != "")
                            {
                                var list = XmlConverter.Deserialize<List<EventRecord>>(sReturnString);
                                if (list != null && list.Count > 0)
                                {
                                    return list;
                                }
                            }
                            else
                            {
                                return null;
                            }
                        }
                    }
                    return null;
                }
            }
        }
        #endregion

        #region 图片下载
        /// <summary>
        /// 下载图片
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public  string DownloadImageFile(string ip ,int port,string filePath)
        {
            string url = "http://" + ip + ":" + port + "/DownloadImageFile" + string.Format("?ImageFilePath={0}",filePath);
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
            //Uid=admin&Pwd=admin&Ip=192.168.186.1&HttpPort=8091
            httpReq.Method = "POST";     //对发送的数据不使用缓存 
            using (Stream postStream = httpReq.GetRequestStream())
            {
                using (WebResponse webRespon = httpReq.GetResponse())
                {
                    using (Stream s = webRespon.GetResponseStream())
                    {
                        //读取服务器端返回的消息
                        using (StreamReader sr = new StreamReader(s))
                        {
                            string sReturnString = sr.ReadToEnd();
                            return sReturnString;
                        }
                    }
                }
            }
        }

        #endregion 

        #region 获取人员信息列表
        /// <summary>
        /// 获取人员信息列表
        /// </summary>
        /// <param name="personType"></param>
        /// <param name="wordKey"></param>
        /// <returns></returns>
        public  List<PersonModel> GetPersonLists(string ip, int port, int personType, string wordKey)
        {
            List<PersonModel> list = new List<PersonModel>();
            string url = "http://" + ip + ":" + port + string.Format("/GetPersonLists?Type={0}&WordKey={1}",personType,wordKey);
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
            httpReq.Method = "POST";     //对发送的数据不使用缓存 
            using (Stream postStream = httpReq.GetRequestStream())
            {
                using (WebResponse webRespon = httpReq.GetResponse())
                {
                    using (Stream s = webRespon.GetResponseStream())
                    {
                        //读取服务器端返回的消息
                        using (StreamReader sr = new StreamReader(s))
                        {
                            string sReturnString = sr.ReadToEnd();

                            if (sReturnString != "")
                            {
                                list = XmlConverter.Deserialize<List<PersonModel>>(sReturnString);
                            }
                        }
                    }
                }
            }
            return list;
        }

        #endregion

        #region 获取人员人脸图片
        /// <summary>
        /// 获取人员人脸图片
        /// </summary>
        /// <param name="personID">人员ID</param>
        /// /// <param name="faceIndex">获取第几个图片 ,从0开始   -1为获取所有</param>
        /// <returns></returns>
        public  List<byte[]> GetPersonFace(string ip, int port, long personID, int faceIndex)
        {
            List<byte[]> byteList = new List<byte[]>();
            string url = "http://" + ip + ":" + port + string.Format("/GetPersonFace?PersonID={0}&FaceIndex={1}",personID,faceIndex);
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
            httpReq.Method = "POST";     //对发送的数据不使用缓存 
            using (Stream postStream = httpReq.GetRequestStream())
            {
                using (WebResponse webRespon = httpReq.GetResponse())
                {
                    using (Stream s = webRespon.GetResponseStream())
                    {
                        //读取服务器端返回的消息
                        using (StreamReader sr = new StreamReader(s))
                        {
                            string sReturnString = sr.ReadToEnd();
                            if (sReturnString != "")
                            {
                                System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
                                xmlDoc.LoadXml(sReturnString);
                                System.Xml.XmlNode xmlNode = xmlDoc.SelectSingleNode("ArrayOfBase64Binary");
                                if ( xmlNode.ChildNodes.Count>0)
                                {
                                    foreach (System.Xml.XmlNode  xmlPicNode in xmlNode.ChildNodes)
                                    {
                                        string b64=  xmlPicNode.InnerText;
                                        byte[] imageBytes=   Convert.FromBase64String(b64);
                                        byteList.Add(imageBytes);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return byteList;
        }

        #endregion

        #region 图片检测人脸
        /// <summary>
        /// 图片检测人脸
        /// </summary>
        /// <param name="picbytes"></param>
        /// <returns></returns>
        public  byte[] GetPersonDetectFace(string ip, int port, byte[] picbytes)
        {
            string url = "http://" + ip + ":" + port + "/GetPersonDetectFace";
            string picB64 = Convert.ToBase64String(picbytes);
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(picB64);
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
            //Uid=admin&Pwd=admin&Ip=192.168.186.1&HttpPort=8091
            httpReq.Method = "POST";     //对发送的数据不使用缓存 
            byte[] relbytes = null;
            using (Stream postStream = httpReq.GetRequestStream())
            {
               //StringContent content = new StringContent(picB64);
                postStream.Write(bytes, 0, bytes.Length);
                using (WebResponse webRespon = httpReq.GetResponse())
                {
                    using (Stream s = webRespon.GetResponseStream())
                    {
                        //读取服务器端返回的消息
                        using (StreamReader sr = new StreamReader(s))
                        {
                            string sReturnString = sr.ReadToEnd();
                            if (!string.IsNullOrEmpty(sReturnString))
                            {
                                byte[] imageBytes = XmlConverter.Deserialize<byte[]>(sReturnString);
                                relbytes = imageBytes;
                            }
                        }
                    }
                }
            }
            return relbytes;
        }

        #endregion

        #region 设置AI通道视频源
        /// <summary>
        /// 设置AI通道视频源
        /// </summary>
        /// <param name="ip">IP地址</param>
        /// <param name="port">端口</param>
        /// <param name="videoSource">AI通道视频源信息</param>
        /// <returns></returns>
        public  string  GetAiChannelVideoSource(string ip, int port,int aiChannelID)
        {
            string url = "http://" + ip + ":" + port + "/GetAiChannelVideoSource?AiChannelID="+aiChannelID+"";
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
            httpReq.Method = "POST";     //对发送的数据不使用缓存 
            using (Stream postStream = httpReq.GetRequestStream())
            {
                using (WebResponse webRespon = httpReq.GetResponse())
                {
                    using (Stream s = webRespon.GetResponseStream())
                    {
                        //读取服务器端返回的消息
                        using (StreamReader sr = new StreamReader(s))
                        {
                            string sReturnString = sr.ReadToEnd();
                            return sReturnString;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 设置AI通道视频源
        /// </summary>
        /// <param name="ip">IP地址</param>
        /// <param name="port">端口</param>
        /// <param name="videoSource">AI通道视频源信息</param>
        /// <returns></returns>
        public bool SetAiChannelVideoSource(string ip, int port, AiChannelVideoSource videoSource)
        {
            if (videoSource == null) return false;
            string url = "http://" + ip + ":" + port + "/SetAiChannelVideoSource";
            string jsonpic = Newtonsoft.Json.JsonConvert.SerializeObject(videoSource);

            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(jsonpic);
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(url);
            httpReq.Method = "POST";     //对发送的数据不使用缓存 
            using (Stream postStream = httpReq.GetRequestStream())
            {
                postStream.Write(bytes, 0, bytes.Length);
                using (WebResponse webRespon = httpReq.GetResponse())
                {
                    using (Stream s = webRespon.GetResponseStream())
                    {
                        //读取服务器端返回的消息
                        using (StreamReader sr = new StreamReader(s))
                        {
                            string sReturnString = sr.ReadToEnd();
                            if (sReturnString == "ok")
                            {
                                return true;
                            }
                            else
                            {
                                return false;
                            }
                        }
                    }
                }
            }
        }

        #endregion 


    }
}
